<?php

namespace App\Http\Controllers\Api;

use App\Http\Services\wxh5pay\config\wxh5pay;
use App\Http\Services\wxh5pay\OrderH5;
use App\InvitingAdvert;
use App\Position;
use App\Resume;
use App\SetTopRecord;
use App\WxAuth;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use App\Http\Requests;
use App\Http\Services\UserManager;
use App\Orders;
use App\User;
use App\Http\Controllers\Controller;

class PaymentController extends Controller
{
    public function wechatAppPay(Request $request){
        $orderNum = $request->get("order_num");
        $payType  = $request->get("pay_type");

        if(is_null($payType) || $payType == ''){
            return response()->json(['level'=>'error','message'=>'咦，系统不知道您是怎么支付的？']);
        }

        if($payType == 'wxapp'){
            $appId = "wx2f9992d76538f26d";
            $notifyUrl = route('Api.Payment.appPayCallback');
        }else{
            $appId = "wx415c26be2370b74f";
            $notifyUrl = route('Api.Payment.wxPayCallback');
        }

        $config = [
            'app_id'             => $appId,
            'mch_id'             => '1519040181',
            'key'                => "b9a2e557d21fc195c50503d40c4b5446",   // API 密钥
            'notify_url'         => $notifyUrl,
        ];

        $app = Factory::payment($config);
        $thatOrder = Orders::whereOrderNum($orderNum)->whereIspay(0)->first();
        if(!$thatOrder){
            return response()->json(['level'=>'error','message'=>'当前订单不存在']);
        }

        $thatUser = User::whereId($thatOrder->user_id)->first();
        if(!$thatUser){
            return response()->json(['level'=>'error','message'=>'用户信息不存在']);
        }

        $wxAuth = WxAuth::whereUserId($thatUser->id)->whereType($payType)->first();
        if(!$wxAuth)
            return response()->json(['level'=>'error','message'=>'系统错误，请重新登录后尝试']);

        $wxOpenId = $wxAuth->wx_openid;

        $result = $app->order->unify([
            'body'         => '置顶服务费',
            'out_trade_no' => $thatOrder->order_num,
            'total_fee'    => $thatOrder->s_amount * 100,
            'notify_url'   => $notifyUrl, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type'   => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid'       => $wxOpenId,
        ]);

        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $jssdk = $app->jssdk;
            $prepayId = $result['prepay_id'];

//            if($payType == 'wxapp'){
                $json = $jssdk->bridgeConfig($prepayId);
//            }else{
//                $json = $jssdk->bridgeConfigWx($prepayId);
//            }

            return response()->json(['level'=>'success','message'=>'获取支付信息成功','data'=>json_decode($json)]);
        }else{
            return response()->json(['level'=>'error','message'=>'创建支付信息失败','data'=>$result]);
        }
    }

    /**
     * 微信H5支付
     */
    public function payByWechatH5(Request $request){
        $orderNum = $request->get('order_num');

        /** @var Orders $thatOrder */
        $thatOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thatOrder)
            return response()->json(['level'=>'error','message'=>'当前订单不存在']);

//        $user = User::whereId($thatOrder->user_id)->first();
//        if(!$user){
//            return response()->json(['level'=>'error','message'=>'用户信息不存在']);
//        }

        $title = '置顶服务费';

        $config = wxh5pay::getConfig();
        $order = new OrderH5($config);
        $order->setParams([
            'body'             => '置顶服务费',
            'detail'           => $title,
            'out_trade_no'     => $orderNum,
            'total_fee'        => (float)$thatOrder->s_amount * 100,
            'trade_type'       => 'MWEB',
            'device_info'      => $config['device_info'],
            'spbill_create_ip' => $request->ip(),
            'notify_url'       => route('Api.Payment.appPayCallback'),
            'scene_info'       => '{"h5_info": {"type":"Wap","wap_url": "http://m.zhaowea.com","wap_name": "找我啊置顶服务费"}}'
        ]);
        $res = $order->unifiedorder();


        if(!$res){
            return response()->json(['level'=>'error','message'=>'创建支付信息失败','data'=>$res]);
        }else {
            return response()->json(['level'=>'success','message'=>trans('获取支付信息成功'),'data'=>$res]);
        }
    }

    public function appPayCallback(Request $request){
        $config = [
            // 必要配置
            'app_id'             => 'wx2f9992d76538f26d',
            'mch_id'             => '1519040181',
            'key'                => 'b9a2e557d21fc195c50503d40c4b5446',
            'notify_url'         => '',
        ];

        $app      = Factory::payment($config);
        $response = $app->handlePaidNotify(function($message, $fail){
            $order = Orders::whereOrderNum($message['out_trade_no'])->first();

            if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
                return true;                 // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->paytime  = date("Y-m-d H:i:s",time()); // 更新支付时间为当前时间
                    $order->pay_type = 'wechat';
                    $order->ispay    = 1;

                    $thatSetTopRecord = SetTopRecord::whereOrderNum($order->order_num)->first();
                    if($thatSetTopRecord){
                        $thatSetTopRecord->start_time = date("Y-m-d H:i:s",time());
                        $thatSetTopRecord->end_time   = date("Y-m-d H:i:s",time() + 3600 * (int)$thatSetTopRecord->hours);
                        $thatSetTopRecord->status     = 1;
                        $thatSetTopRecord->save();

                        if($thatSetTopRecord->remark == "position"){
                            $thatPosition = Position::whereId($thatSetTopRecord->position_id)->first();
                            if($thatPosition){
                                $thatPosition->set_top = 1;
                                $thatPosition->save();
                            }
                        }
                        if($thatSetTopRecord->remark == "resume"){

                            $thatResume=Resume::whereId($thatSetTopRecord->resume_id)->first();
                            if($thatResume){
                                $thatResume->set_top=1;
                                $thatResume->save();

                            }
                        }else{
                            $thatAdvent = InvitingAdvert::whereId($thatSetTopRecord->advent_id)->first();
                            if($thatAdvent){
                                $thatAdvent->set_top = 1;
                                $thatAdvent->save();
                            }
                        }

                    }

                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->ispay = 0;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            $order->save();

            return true;
        });

        return $response;
    }

    public function wxPayCallback(Request $request){
        $config = [
            // 必要配置
            'app_id'             => 'wx415c26be2370b74f',
            'mch_id'             => '1519040181',
            'key'                => 'b9a2e557d21fc195c50503d40c4b5446',
            'notify_url'         => '',
        ];

        $app      = Factory::payment($config);
        $response = $app->handlePaidNotify(function($message, $fail){
            $order = Orders::whereOrderNum($message['out_trade_no'])->first();

            if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
                return true;                 // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->paytime  = date("Y-m-d H:i:s",time()); // 更新支付时间为当前时间
                    $order->pay_type = 'wechat';
                    $order->ispay    = 1;

                    $thatSetTopRecord = SetTopRecord::whereOrderNum($order->order_num)->first();
                    if($thatSetTopRecord){
                        $thatSetTopRecord->start_time = date("Y-m-d H:i:s",time());
                        $thatSetTopRecord->end_time   = date("Y-m-d H:i:s",time() + 3600 * (int)$thatSetTopRecord->hours);
                        $thatSetTopRecord->status     = 1;
                        $thatSetTopRecord->save();

                        if($thatSetTopRecord->remark == "position"){
                            $thatPosition = Position::whereId($thatSetTopRecord->position_id)->first();
                            if($thatPosition){
                                $thatPosition->set_top = 1;
                                $thatPosition->save();
                            }
                        }

                        if($thatSetTopRecord->remark == "resume"){
                            $thatResume = Resume::whereId($thatSetTopRecord->resume_id)->first();
                            if($thatResume){
                                $thatResume->set_top = 1;
                                $thatResume->save();
                            }
                        }
                        else{
                            $thatAdvent = InvitingAdvert::whereId($thatSetTopRecord->advent_id)->first();
                            if($thatAdvent){
                                $thatAdvent->set_top = 1;
                                $thatAdvent->save();
                            }
                        }
                    }

                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->ispay = 0;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            $order->save();

            return true;
        });

        return $response;
    }
}
